package JavaAssignment;
import java.io.*;
public class LinkList implements Serializable{

  private int noOfElement = 0;
  private ListNode headnode = null;

  public LinkList() {}

  public LinkList(Object data) {
    add(0,data);
  }

  public boolean isEmpty() {
    return noOfElement == 0;
  }

  public int getNoOfElement() {
    return noOfElement;
  }

  private ListNode find(int index) {
    ListNode currnode = headnode;
    for (int i = 0; i < index; i++) {
      currnode = currnode.getNext();
    }
    return currnode;
  }

  public Object get(int index) throws IndexOutOfBoundsException {

    if (index >= 0 && index < noOfElement) {
      ListNode currnode = find(index);
      Object data = currnode.getData();
      return data;
    }
    else {
      throw new IndexOutOfBoundsException(
          "index out of bounds exception on get");
    }

  }


  public void add(int index, Object data) throws IndexOutOfBoundsException {

    if (index >= 0 && index <= noOfElement+1) {
      if (index == 0) {
        ListNode newnode = new ListNode(data, headnode);
        headnode = newnode;
      }
      else {
        ListNode prevnode = find(index - 1);
        ListNode newnode = new ListNode(data, prevnode.getNext());
        prevnode.setNext(newnode);
      }
      noOfElement++;
    }
    else {
      throw new IndexOutOfBoundsException(
          "index out of bounds exception on add");
    }
  }

  public void addLast(Object data) throws IndexOutOfBoundsException {
     add(noOfElement, data);
  }

  public void remove(int index) throws IndexOutOfBoundsException {

    if (index >= 0 && index <= noOfElement) {
      if (index == 0) {
        headnode = headnode.getNext();
      }
      else {
        ListNode prevnode = find(index - 1);
        ListNode currnode = prevnode.getNext();
        prevnode.setNext(currnode.getNext());
      }
      noOfElement--;
    }else {
      throw new IndexOutOfBoundsException(
          "index out of bounds exception on remove");
    }
  }

  public void removeAll() {
    headnode = null;
    noOfElement = 0;
  }

} // end LinkList
